package com.paradogs.framework.gate;

import com.paradogs.framework.core.msg.PRMsgContextHolder;
import io.netty.channel.Channel;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.HashMap;
import java.util.Map;

/**
 * @author: yumi
 * @date: 2023/12/1  11:27
 * @Description: 玩家连接管理
 */
public class GateChannelHolder {

    /**
     * map[channel] = session
     */
    private static Map<Channel, Session> channelMap = new HashMap<>();
    /**
     * map[playerId] = channel
     */
    private static Map<Long, Channel> playerMap = new HashMap<>();


    public static void init(Channel channel) {
        channelMap.put(channel, null);
    }
    public static void remove(Channel channel) {
        Session session = channelMap.remove(channel);
        if (session != null && session.getPlayerId() != null) {
            playerMap.remove(session.getPlayerId());
        }
    }

    /**
     * 获得 Channel 对应数据
     * @param channel
     * @return
     */
    public static Session getSession(Channel channel) {
        return channelMap.get(channel);
    }

    /**
     * 绑定 Channel 数据
     * @param channel
     * @param session
     */
    public static void bindSession(Channel channel, Session session) {
        channelMap.put(channel, session);
        playerMap.put(session.getPlayerId(), channel);
        // 重新设置当前上下文
        PRMsgContextHolder.Snapshot snapshot = PRMsgContextHolder.getSnapshot();
        snapshot.setPlayId(session.getPlayerId());
        PRMsgContextHolder.setContext(snapshot);
    }

    /**
     * 获取玩家 ID 的 Channel
     * @param playerId
     * @return
     */
    public static Channel getPlayerChannel(Long playerId) {
        return playerMap.get(playerId);
    }

    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public static class Session {
        private Long playerId;
    }

}
